#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"

void Swap(heapDatatype* a, heapDatatype* b)
{
	heapDatatype tmp = *a;
	*a = *b;
	*b = tmp;
}

void HeadInit(struct Heap* php)
{
	assert(php);
	php->a = NULL;
	php->size = 0;
	php->capacity = 0;
}

void HeapDestory(struct Heap* php)
{
	free(php->a);
	php->a == NULL;
	php->size = php->capacity = 0;
	
}

void HpJumpUp(struct Heap* php, int Child)
{
	assert(php);
	int parent = (Child - 1) / 2;
	while (Child > 0)
	{
		if (php->a[Child] > php->a[parent])
		{
			Swap(&(php->a[Child]), &(php->a[parent]));
			Child = parent;
			parent = (Child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HpJumpDown(struct Heap* php, int parent)
{
	int Child = parent * 2 + 1;
	while (Child < php->size && Child + 1 < php->size)
	{
		if (php->a[Child] < php->a[Child + 1])
		{
			Child++;
		}
		if (php->a[Child] > php->a[parent])
		{
			Swap(&php->a[Child], &php->a[parent]);
			parent = Child;
			Child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HeapPush(struct Heap* php, heapDatatype x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int newCapacity = php->capacity == 0 ? 4 : 2 * php->capacity;
		struct HP* tmp = (struct HP*)realloc(php->a, sizeof(heapDatatype) * newCapacity);
		php->a = tmp;
		php->capacity = newCapacity;
	}
	php->a[php->size] = x;
	HpJumpUp(php, php->size);
	php->size++;

	
}

void HeapPop(struct Heap* php)
{
	int Child = php->size - 1;
	int parent = 0;
	Swap(&php->a[Child], &php->a[parent]);
	php->size--;
	HpJumpDown(php, 0);
}

void HeapPrintf(struct Heap* php)
{
	assert(php);
	int i = 0;
	for (i = 0; i < php->size; i++)
	{
		printf("%d ", php->a[i]);
	}
}

heapDatatype HeapTop(struct Heap* php)
{
	assert(php);
	assert(php->size > 0);
	return php->a[0];

}